package com.yd.app.service.pc.couponService;

import com.yd.app.mapper.CouponMapper;
import com.yd.app.service.common.BaseService;
import com.yd.domain.business.Coupon;
import com.yd.domain.business.UserCouponSend;
import com.yd.domain.commom.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 优惠券Service
 * Created by sunxianhui on 2018/3/9.
 */
@Service
public class CouponService extends BaseService {
    @Autowired
    CouponMapper couponMapper;

    /**
     * 添加优惠券
     *
     * @param coupon
     */
    public int addCoupon(Coupon coupon) {
        return couponMapper.addCoupon(coupon);
    }

    /**
     * 修改
     *
     * @param coupon
     */
    public void updateCoupon(Coupon coupon) {
        couponMapper.updateCoupon(coupon);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteCouponByid(String id) {
        couponMapper.deleteCouponById(id);
    }

    /**
     * 根据条件分页查询
     *
     * @param coupon
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public PageModel getCouponList(Coupon coupon, int pageIndex, int pageSize) {
        PageModel pm = new PageModel();
        int startRow = getStartRow(pageIndex, pageSize);
        List<Coupon> couponList = couponMapper.getCouponList(coupon, startRow, pageSize);
        for(Coupon cou:couponList){
            if(cou.getEndDate().getTime()<new Date().getTime()){
                cou.setIfCanUse(false);
            }else{
                cou.setIfCanUse(true);
            }
        }
        int count = 0;
        if (pageIndex == 1) {
            //查询总条数
            count = couponMapper.getCouponCount(coupon);
            pm.setCount(count);
        }
        pm.setList(couponList);
        return pm;
    }

    public Coupon getCouponById(String id) {
        Coupon coupon=couponMapper.getCouponById(id);
        return coupon;
    }

    @Transactional
    public void sendCouponToUser(UserCouponSend ucs) {
        for(String userId:ucs.getUserIds()){
            couponMapper.addUserCoupon(userId,ucs.getCouponId(),ucs.getNumber());
        }
    }
}